<template>
  <div class="content">
    <!-- 粒子效果 -->
    <vue-particles 
      class="vue-particles" 
      color="#dedede" 
      :particleOpacity="0.7" 
      :particlesNumber="60" 
      shapeType="star" 
      :particleSize="4" 
      linesColor="#dedede" 
      :linesWidth="1" 
      :lineLinked="true" 
      :lineOpacity="0.4" 
      :linesDistance="150" 
      :moveSpeed="3" 
      :hoverEffect="true" 
      hoverMode="grab" 
      :clickEffect="true" 
      clickMode="push">
    </vue-particles>
    <div class="title">仲易学后台管理系统</div>
    <div class="loginBox">
      <div class="loginText">登录</div>
      <el-form
        ref="loginFormByPasswordRef"
        :model="loginFormByPassword"
        :rules="loginFormRulesByPassword"
        label-width="0px"
        class="login_form"
      >
        <el-form-item label="" prop="username" style="margin-top: 40px">
          <el-input
            class="inps"
            placeholder="请输入用户名"
            v-model="loginFormByPassword.username"
            prefix-icon="el-icon-user-solid"
            @keyup.enter.native="enterKey"
          ></el-input>
        </el-form-item>
        <el-form-item label="" prop="password">
          <el-input
            class="inps"
            placeholder="请输入密码"
            v-model="loginFormByPassword.password"
            prefix-icon="el-icon-lock"
            type="password"
            @keyup.enter.native="enterKey"
          ></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input
            style="width: 110px"
            class="inps"
            v-model="loginFormByPassword.captcha"
            placeholder="输入验证码"
            @keyup.enter.native="enterKey"
          >
          </el-input>
          <el-image 
            @click="getCaptchaImg()"
            style="
              width: 120px;
              position: absolute;
              height: 42px;
              margin-left: 20px;
            " 
            :src="url"
          ></el-image>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-checkbox v-model="remeberPassword" class="remember">记住密码</el-checkbox>
          </el-col>
          <el-col :span="12">
            <span class="tips">忘记密码？</span>
          </el-col>
        </el-row>
        <el-form-item style="margin-top: 25px; text-align: center">
          <el-button
            type="primary"
            @click="loginByPassword"
            class="submitBtn"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login, getCaptch } from "../../../api/Login/login.js";
export default {
  name: 'login',
  data() { 
    return {
      id: 1,
      // 标签名
      loginName: "password",
      // 验证码地址
      url: "",
      // 验证码图片（jpeg图片，Base64编码）
      //captchaImg:"",
      // 验证码
      requestCaptcha: "",
      // 是否记住密码：
      remeberPassword: false,
      // 发送邮件验证码的按钮是否可用
      disButton: false,
      // 密码登录的表单
      loginFormByPassword: {
        username: "",
        password: "",
        captcha: "",
      },
      // 密码登录表单的验证规则对象
      loginFormRulesByPassword: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码长度在6到15个字符",
            trigger: "blur",
          },
        ],
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            min: 4,
            max: 4,
            message: "验证码长度为4个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    // 获取验证码
    this.getCaptchaImg();
    this.getCookie();
  },
  beforeDestroy(){
    if(pJSDom && pJSDom.length > 0){          
      pJSDom.forEach(pJSDomItem=>{               
        pJSDomItem.pJS.fn.vendors.destroypJS()          
      })     
    }
  },
  methods: {
    // 获取验证码
    async getCaptchaImg() {
      this.url = await getCaptch()
      //this.url = await getHCaptch() //登录用hlogin
    },
    enterKey(e) {
      if(e.keyCode === 13) {
        this.loginByPassword();
      }
    },
    async loginByPassword() {
      // 将验证码全部转换成小写
      this.loginFormByPassword.captcha =
        this.loginFormByPassword.captcha.toLowerCase();
      console.log(this.loginFormByPassword);
      // 表单验证通过后再请求登录
      this.$refs.loginFormByPasswordRef.validate(async (valid) => {
        if (!valid) return false;
        // 调用登录接口
        //const { data: res } = await hlogin(this.loginFormByPassword);
        const { data: res } = await login(this.loginFormByPassword);
        console.log(res);
        if (res.ret !== 0) {
          this.getCaptchaImg();
          return this.$message.error(res.msg);
        }
        this.$message.success("登录成功！");
        // 1、将登录成功后的token，保存到客户端的 sessionStorage 中
        //  1.1 项目中除了登录的其他API接口，必须在登录后才能访问
        //  1.2 token 只在当前网站打开期间有效，所以将 token 保存在 sessionStoarg 中
        window.sessionStorage.setItem("token", res.token);
        window.sessionStorage.setItem("userId", res.userId + '');
        window.sessionStorage.setItem("permis", JSON.stringify(res.permis))
        // 如果选择了记住密码，就将用户名和密码存储到cookie中
        if (this.remeberPassword) {
          this.setCookie(
            this.loginFormByPassword.username,
            this.loginFormByPassword.password,
            7
          );
        }
        // 2、通过编程式导航跳转到后台主页，路由地址是 /home
        this.$router.push("/");
      });
    },

    // 设置cookie
    setCookie(username, password, days) {
      let existDay = new Date();
      // 设置 cookie 的有效期
      existDay.setTime(existDay.getTime() + 24 * 60 * 60 * 1000 * days);
      //字符串拼接cookie
      window.document.cookie =
        "userName" +
        "=" +
        username +
        ";path=/;expires=" +
        existDay.toGMTString();
      window.document.cookie =
        "password" +
        "=" +
        password +
        ";path=/;expires=" +
        existDay.toGMTString();
    },

    // 获取cookie
    getCookie() {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); //这里显示的格式需要切割一下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); //再次切割
          //判断查找相对应的值
          if (arr2[0] == "userName") {
            this.loginFormByPassword.username = arr2[1];
          } else if (arr2[0] == "password") {
            this.loginFormByPassword.password = arr2[1];
          }
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.content {
  width: 100vw;
  padding: 0;
  margin: 0;
  height: 100%;
  font-size: 16px;
  background: #232741;
  background-size: 100%;
  position: relative;
  .title {
    color: white;
    font-weight: bold;
    font-size: 45px;
    letter-spacing: 10px;
    position: absolute;
    top: 45px;
    left: 50%;
    transform: translate(-50%, 0);
  }
  .loginBox {
    width: 450px;
    height: 380px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: auto;
    padding: 80px 50px 50px 40px;
    opacity: 1;
    border-radius: 20px;
    .loginText {
      color: white;
      font-weight: bold;
      text-align: center;
      font-size: 20px;
    }
    /deep/ .inps input {
      color: white;
      background-color: #2A3543;
      font-size: 12px;
      border: none;
      opacity: 0.5;
    }
    .submitBtn {
      background-color: #419eff;
      width: 450px;
      color: #fff;
    }
    .remember, .tips {
      color: white;
      font-size: 13px;
      cursor: pointer;
    }
    .tips {
      float: right;
    }
  }
}
</style>
